export function formatTime(second) {
	var sec = second % 60;
	var min = Math.floor(second / 60);
	if (min.toString().length < 2) {
		min = '0' + min;
	}
	if (sec.toString().length < 2) {
		sec = '0' + sec;
	}
	return min + ':' + sec
}

export function getAge(strAge) {
	if (!strAge) return ''
	var birArr = strAge.split("-");
	var birYear = birArr[0];
	var birMonth = birArr[1];
	var birDay = birArr[2];

	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1; //记得加1
	var nowDay = d.getDate();
	var returnAge;

	if (birArr == null) {
		return false
	};
	var d = new Date(birYear, birMonth - 1, birDay);
	if (d.getFullYear() == birYear && (d.getMonth() + 1) == birMonth && d.getDate() == birDay) {
		if (nowYear == birYear) {
			returnAge = 0; // 
		} else {
			var ageDiff = nowYear - birYear; // 
			if (ageDiff > 0) {
				if (nowMonth == birMonth) {
					var dayDiff = nowDay - birDay; // 
					if (dayDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				} else {
					var monthDiff = nowMonth - birMonth; // 
					if (monthDiff < 0) {
						returnAge = ageDiff - 1;
					} else {
						returnAge = ageDiff;
					}
				}
			} else {
				return "出生日期晚于今天，数据有误"; //返回-1 表示出生日期输入错误 晚于今天
			}
		}
		return returnAge;
	} else {
		return ("输入的日期格式错误！");
	}
}

export function dateFormat(dateObj, format) {
	const date = {
		'M+': dateObj.getMonth() + 1,
		'd+': dateObj.getDate(),
		'h+': dateObj.getHours(),
		'm+': dateObj.getMinutes(),
		's+': dateObj.getSeconds(),
		'q+': Math.floor((dateObj.getMonth() + 3) / 3),
		'S+': dateObj.getMilliseconds(),
	}
	if (/(y+)/i.test(format)) {
		format = format.replace(
			RegExp.$1,
			(dateObj.getFullYear() + '').substr(4 - RegExp.$1.length)
		)
	}
	for (const k in date) {
		if (new RegExp('(' + k + ')').test(format)) {
			format = format.replace(
				RegExp.$1,
				RegExp.$1.length === 1 ?
				date[k] :
				('00' + date[k]).substr(('' + date[k]).length)
			)
		}
	}
	return format
}

export function randomString(num) {
	const chars = [
		'0',
		'1',
		'2',
		'3',
		'4',
		'5',
		'6',
		'7',
		'8',
		'9',
		'a',
		'b',
		'c',
		'd',
		'e',
		'f',
		'g',
		'h',
		'i',
		'j',
		'k',
		'l',
		'm',
		'n',
		'o',
		'p',
		'q',
		'r',
		's',
		't',
		'u',
		'v',
		'w',
		'x',
		'y',
		'z',
	]
	let res = ''
	for (let i = 0; i < num; i++) {
		var id = Math.ceil(Math.random() * 35)
		res += chars[id]
	}
	return res
}

// 保存图片
let settingWritePhotosAlbum = false;
export const saveImg = function(url, callback) {
	if (url) {
		uni.downloadFile({
			url: url,
			success: data => {
				if (data.statusCode == 200) {
					console.log(data.tempFilePath)
					uni.saveImageToPhotosAlbum({
						filePath: data.tempFilePath,
						success: () => {
							callback && callback();
							uni.showToast({
								title: '保存成功'
							});
						}
					});
				}
			}
		});
	} else {
		uni.showToast({
			title: '未找到图片',
			icon: 'none'
		});
	}
};